package com.sum.tea.viewmodel

import androidx.lifecycle.ViewModel
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ToastUtils
import com.sum.common.bean.LockParams
import com.sum.common.bean.ReaderExt.Lock_Obj
import com.sum.common.bean.ReaderExt.Lock_Type
import com.sum.common.bean.ReaderExt.READER_ERR
import com.sum.common.manager.UHFManager
import com.sum.common.utils.ByteUtil

class LockViewModel : ViewModel() {
    fun lockTag(params: LockParams) {
        val (lockObj, lockType) = getLockObjAndType(params.regionPosition, params.lockTypePosition)
        val passWord = if(UHFManager.getInstance().isXinlianDevice){
            val rpaswd = ByteArray(4)
            if(params.accessPassword.isNotEmpty()){
                ByteUtil.Str2Hex(params.accessPassword, params.accessPassword.length,rpaswd)
            }
            rpaswd
        }else {
            ConvertUtils.hexString2Bytes(params.accessPassword)
        }

        val result = UHFManager.getInstance().currentManager.lockTag(
            lockObj,
            lockType,
            passWord,
            1000
        )

        if (result == READER_ERR.MT_OK_ERR) {
            ToastUtils.showShort("锁定成功")
        } else {
            ToastUtils.showShort("锁定失败")
        }
    }

    private fun getLockObjAndType(regionPos: Int, lockPos: Int): Pair<Lock_Obj, Lock_Type> {
        return when (regionPos) {
            0 -> Lock_Obj.LOCK_OBJECT_ACCESS_PASSWD to when (lockPos) {
                0 -> Lock_Type.ACCESS_PASSWD_UNLOCK
                1 -> Lock_Type.ACCESS_PASSWD_LOCK
                else -> Lock_Type.ACCESS_PASSWD_PERM_LOCK
            }
            1 -> Lock_Obj.LOCK_OBJECT_KILL_PASSWORD to when (lockPos) {
                0 -> Lock_Type.KILL_PASSWORD_UNLOCK
                1 -> Lock_Type.KILL_PASSWORD_LOCK
                else -> Lock_Type.KILL_PASSWORD_PERM_LOCK
            }
            2 -> Lock_Obj.LOCK_OBJECT_BANK1 to when (lockPos) {
                0 -> Lock_Type.BANK1_UNLOCK
                1 -> Lock_Type.BANK1_LOCK
                else -> Lock_Type.BANK1_PERM_LOCK
            }
            3 -> Lock_Obj.LOCK_OBJECT_BANK2 to when (lockPos) {
                0 -> Lock_Type.BANK2_UNLOCK
                1 -> Lock_Type.BANK2_LOCK
                else -> Lock_Type.BANK2_PERM_LOCK
            }
            4 -> Lock_Obj.LOCK_OBJECT_BANK3 to when (lockPos) {
                0 -> Lock_Type.BANK3_UNLOCK
                1 -> Lock_Type.BANK3_LOCK
                else -> Lock_Type.BANK3_PERM_LOCK
            }

            else -> {
                Lock_Obj.LOCK_OBJECT_ACCESS_PASSWD to Lock_Type.ACCESS_PASSWD_UNLOCK
            }
        }
    }
}
